package com.xinyun.traceability.utils;

import com.xinyun.traceability.enity.po.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CommonUtil {

    private static Logger logger = LoggerFactory.getLogger(CommonUtil.class);

    /**
     * 	获取当前登录用户
     * @return
     */
    public static SysUser getCurrentUser() {
        HttpServletRequest request = getHttpServletRequest();
        if (request == null) {
            logger.warn("request为null");
            return null;
        }
        if (request.getSession() == null) {
            return null;
        }
        Object user = request.getSession().getAttribute("sysUser");
        if (user == null) {
            logger.warn("user为null");
            return null;
        }
        return (SysUser) user;
    }

    /**
     * 获取 HttpServletRequest
     * @return
     */
    public static HttpServletRequest getHttpServletRequest() {
        if(RequestContextHolder.getRequestAttributes() == null) {
            return null;
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    public static HttpServletResponse getResponse(){
        HttpServletResponse resp = ((ServletWebRequest)RequestContextHolder.getRequestAttributes()).getResponse();
        return resp;
    }


}
